<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>选择</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <style>
    
   
    /* 设置 canvas 的初始显示位置 */
    #myCanvas {
       position: relative;  /* 或者使用 'relative', 'fixed', 或 'sticky' */
       top: 10px;         /* 距离顶部的距离 */
       left: 100px;         /* 距离左边的距离 */
      
       border: 1px solid #ccc; /* 设置 canvas 的边框颜色 */
       z-index: 1;
     }

     .button-container {
    position: relative; /* 为了定位 canvas */
    display: inline-block; /* 使容器适应内容宽度 */
  }

  #menuCanvas {
    z-index: 2; /* Ensures that the menuCanvas is above the mainCanvas */
    display: none; /* Initially hide the menu canvas */
    position: absolute;
    border: 1px solid #ddd;
  }


  .button {
    padding: 10px;
    border: 2px solid transparent; /* 默认透明边框 */
    background-color: transparent;
    cursor: pointer;
    font-size: 16px;
    text-align: center;
    display: flex;
    flex-direction: column; /* 垂直排列内容 */
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    transition: border 0.3s; /* 平滑过渡效果 */
  }

  .button:hover {
    border-color: #f2f2f2; /* 鼠标悬停时显示边框 */
  }

  .button img {
    width: 20px;
    height: 20px;
  }

  .button span {
    margin-top: 5px; /* 文本上方间隔 */
  }

  .canvas-popup {
    display: none;
    position: absolute; /* 绝对定位 */
    z-index: 10; /* 确保画布位于按钮之上 */
    background: #fff;
    box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.2); /* 外部阴影 */
  }

  /* 调整画布尺寸以匹配网格 */
  #canvasPopup {
    width: 300px; /* 宽度为5个单元格+50像素的偏移 */
    height:520px; /* 高度为5个单元格+50像素的偏移 */
  }


    </style>
&nbsp;&nbsp;
<div class="button-container">
  <button class="button" id="showGrid">
    <img src="imgs/insert_table.png" alt="Grid Icon"/>
    <span>插入表格</span>
  </button>
</div>



    <div id="cursorCoordinates"></div>

<canvas id="canvasPopup" class="canvas-popup" width="300" height="520"></canvas>
<canvas id="myCanvas" width="1300" height="1200"></canvas>
<canvas id="menuCanvas" width="800" height="500"></canvas>
<script>

  // 画布上页面的位置和大小
  const pageX = 20; // 画布左边界偏移20像素
  const pageY = 20; // 画布上边界偏移20像素
  const pageWidth = 794; // 页面宽度
  const pageHeight = 1123; // 页面高度
  var   lastTableTotalWidth=0;  //最新的表格宽度更新
  var   selectStartX=0;  //选中表格的起始X坐标
  var   selectStartY=0;  //选中表格的起始Y坐标
  var   isSelecting = false;
  var   selectionStart = {};
  var   selectedCells = [];
  var   currentSelection = [];//记录当前选择单元各的 数组下标集
  var   jsonData = [];
  var   tableTotalWidth=0;
  var   tableTotalHeight=0;
  var   tableOffsetX=60;  //表格与画布的左边距
  var   tableOffsetY=110; //表格与画布的顶边距
  var   whereCurIs=0;     //在表格边上悬浮 1,光标在单元格的上边线上, 2光标在左侧边; 3光标在第一行的上边; 4，在最下边单元格；5光标在单元格内部
  var   cursorIsInSideOfCell=0;//光标在单元格内部，，offset之内

  var canvas1 = $('#canvasPopup')[0];
  var menuCanvas = document.getElementById('menuCanvas');

  var menuCtx = menuCanvas.getContext('2d');

  var ctx1 = canvas1.getContext('2d');
  var gridSize = 15;
  var gridSpacing = 5;
  var rowSpacing = 5;
  var rows = 24, columns = 14;
  var gridColor = '#000';
  var highlightColor = 'rgba(173, 216, 230, 0.5)'; // Light blue color


  const menuItemHeight = 50;
const menuItems = ["合并单元格", "取消"];
let selectedMenuItem = -1;

function drawRoundedRect(ctx, x, y, width, height, radius, fillStyle) {
  ctx.fillStyle = fillStyle;
  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.arcTo(x + width, y, x + width, y + height, radius);
  ctx.arcTo(x + width, y + height, x, y + height, radius);
  ctx.arcTo(x, y + height, x, y, radius);
  ctx.arcTo(x, y, x + width, y, radius);
  ctx.closePath();
  ctx.fill();
}

function drawMenu() {
  // Draw background
  drawRoundedRect(menuCtx, 0, 0, menuCanvas.width, menuCanvas.height, 10, 'white');

  // Draw menu items
  menuItems.forEach((item, index) => {
    menuCtx.fillStyle = index === selectedMenuItem ? '#add8e6' : 'white';
    menuCtx.fillRect(0, menuItemHeight * index, menuCanvas.width, menuItemHeight);
    
    // Draw text
    menuCtx.fillStyle = 'black';
    menuCtx.font = '16px Arial';
    menuCtx.textBaseline = 'middle';
    menuCtx.textAlign = 'center';
    menuCtx.fillText(item, menuCanvas.width / 2, menuItemHeight * (index + 0.5));
  });

  // Add shadow
  menuCtx.shadowOffsetX = 0;
  menuCtx.shadowOffsetY = 2;
  menuCtx.shadowBlur = 4;
  menuCtx.shadowColor = 'rgba(0, 0, 0, 0.5)';
  drawRoundedRect(menuCtx, 0, 0, menuCanvas.width, menuCanvas.height, 10, 'transparent');
}

function showMenu(x, y) {
  menuCanvas.style.left = `{x}px`;
  menuCanvas.style.top = `{y}px`;
  menuCanvas.style.display = 'block';
  drawMenu();
}

function hideMenu() {
  menuCanvas.style.display = 'none';
}

  function drawTableFromJson(jsonData) {
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  canvas.width = jsonData[0].cells.reduce((acc, cell) => acc + cell.width, 0);
  canvas.height = jsonData.length * jsonData[0].cells[0].height;
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  var currentX = 0;
  var currentY = 0;

  


  jsonData.forEach(function(rowData, rowIndex) {
    currentX = 0;
    rowData.cells.forEach(function(cell) {
      if (cell.showBorder) {
        ctx.strokeRect(currentX, currentY, cell.width, cell.height);
      }
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.fillText(cell.content, currentX + cell.width / 2, currentY + cell.height / 2);
      currentX += cell.width;
    });
    currentY += rowData.cells[0].height;
  });
}

 // Function to draw the icon on the canvas
 function drawIcon(x, y) {
    if (iconLoaded && iconVisible) {
      // Clear the canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      
      // Draw the icon
      ctx.drawImage(icon, x - icon.width / 2, y - icon.height / 2);
    }
  }

  // Function to draw the grid
  function drawGrid() {
    ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
    ctx1.beginPath();
    for (var row = 0; row < rows; row++) {
      for (var col = 0; col < columns; col++) {
        ctx1.rect(
          gridSpacing + col * (gridSize + gridSpacing),
          gridSpacing + row * (gridSize + rowSpacing),
          gridSize,
          gridSize
        );
      }
    }
    ctx1.strokeStyle = gridColor;
    ctx1.stroke();
  }



  // Function to highlight squares
  function highlightSquares(x, y) {
    var colEnd = Math.floor(x / (gridSize + gridSpacing));
    var rowEnd = Math.floor(y / (gridSize + rowSpacing));

    colEnd = colEnd >= columns ? columns - 1 : colEnd;
    rowEnd = rowEnd >= rows ? rows - 1 : rowEnd;

    for (var row = 0; row <= rowEnd; row++) {
      for (var col = 0; col <= colEnd; col++) {
        ctx1.fillStyle = highlightColor;
        ctx1.fillRect(
          gridSpacing + col * (gridSize + gridSpacing),
          gridSpacing + row * (gridSize + rowSpacing),
          gridSize,
          gridSize
        );
      }
    }



    // Display the selection info
    $('#showInfo').text('Selected Rows: ' + (rowEnd + 1) + ', Columns: ' + (colEnd + 1));
    
    return { rows: rowEnd + 1, columns: colEnd + 1 };
  }
  
 



    // 监听按钮点击事件
    document.getElementById('showGrid').addEventListener('click', function(event) {
    const button = event.currentTarget;
    const canvas = document.getElementById('canvasPopup');
    const buttonRect = button.getBoundingClientRect();

    // 设置 canvas 位置在按钮的左下方
    canvas.style.top = buttonRect.bottom + window.scrollY + 'px'; // 添加滚动偏移
    canvas.style.left = buttonRect.left + window.scrollX + 'px'; // 添加滚动偏移

    // 切换 canvas 的显示状态
    canvas.style.display = (canvas.style.display === 'block') ? 'none' : 'block';

    // 绘制格子，如果 canvas 已显示
    if (canvas.style.display === 'block') {
     // drawGrid(canvas);
     drawGrid(); // Initial grid draw
    }
  });
  
// 传入边距值和行列数来绘制表格
  // 假设用户输入的边距值为10mm
  var marginTop = 10; // 上边距
  var marginBottom = 10; // 下边距
  var marginLeft = 10; // 左边距
  var marginRight = 10; // 右边距
  
  // 假设上次选中的行列数
  var lastSelectedRows = 0;
  var lastSelectedCols = 0;
/*
"cells": [
        {"content": "A1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
*/

  function generateJsonData(rows, columns) {
    if(rows==0||columns==0)
    return;
   var cellWidth=720/columns;
   var cellHeight=32;
   jsonData = [];
  for (var i = 0; i < rows; i++) {
    var row = { "cells": [] };
    for (var j = 0; j < columns; j++) {
      row.cells.push({ "content": String.fromCharCode(65 + j) + (i + 1), "width": cellWidth, "height": cellHeight, "borderSize": 1, "showBorder": true });
    }
    jsonData.push(row);
  }
  return jsonData;
}

  // Mousedown event to confirm selection and hide the first layer
  

  function drawTableOnLayer2WithMargins(rows, cols, marginTop, marginBottom, marginLeft, marginRight) {
    var canvas2 = document.getElementById('myCanvas');
    var ctx2 = canvas2.getContext('2d');
    var a4WidthPixels = 793; // A4宽度，单位为像素
    var a4HeightPixels = 1122; // A4高度，单位为像素
  
    // 边距转换为像素，这里假设边距是以毫米为单位输入的
    var marginTopPixels = marginTop * 3.78;
    var marginBottomPixels = marginBottom * 3.78;
    var marginLeftPixels = marginLeft * 3.78;
    var marginRightPixels = marginRight * 3.78;
  
    // 计算可用于表格的宽度和高度
    var usableWidth = a4WidthPixels - marginLeftPixels - marginRightPixels;
    var usableHeight = 40*3.78*rows;//a4HeightPixels - marginTopPixels - marginBottomPixels;
  
    // 根据可用宽度和高度计算单元格的宽度和高度
    var cellWidth = usableWidth / cols;
    var cellHeight = 40;//usableHeight / rows;
  
    // 清除之前的绘制
    ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
  
    // 开始绘制表格
    ctx2.beginPath();
    for (var row = 0; row < rows; row++) {
      for (var col = 0; col < cols; col++) {
        ctx2.rect(marginLeftPixels + col * cellWidth, marginTopPixels + row * cellHeight, cellWidth, cellHeight);
      }
    }
    ctx2.strokeStyle = 'black';   // 设置线条颜色
    ctx2.stroke();                // 绘制表格线条
  }
  $(document).ready(function() {


    $(document).on("contextmenu", function(e) {
    e.preventDefault(); // 阻止默认的右键菜单弹出
    });


//     // Click event listener for the main canvas
// mainCanvas.addEventListener('click', function(e) {
//   var rect = mainCanvas.getBoundingClientRect();
//   var x = e.clientX - rect.left;
//   var y = e.clientY - rect.top;
//   showMenu(x, y);
// });

// Click event listener for the menu canvas
menuCanvas.addEventListener('click', function(e) {
  var rect = menuCanvas.getBoundingClientRect();
  var x = e.clientX - rect.left;
  var y = e.clientY - rect.top;

  // Determine if a menu item was clicked
  if (y < menuItemHeight) {
    // "合并单元格" was clicked
    console.log('合并单元格 was clicked');
  } else if (y < menuItemHeight * 2) {
    // "取消" was clicked
    console.log('取消 was clicked');
  }

  // Hide the menu
  hideMenu();
});

// Initial hide of the menu canvas
	hideMenu();
  function drawCoordinates(x, y) {
  // Clear the canvas
  ctx1.clearRect(0, canvas1.height-12, canvas1.width, canvas1.height);
  
  // Optionally redraw other stuff here, e.g., a grid
  
  // Draw the coordinates
  ctx1.font = '14px Arial';
  ctx1.fillStyle = '#808080'; // Light blue color
  ctx1.fillText(x + '行 * ' +y+ '列 表格', 10, canvas1.height - 10);
}




          // Mousemove event to highlight squares
  $('#canvasPopup').mousemove(function(e) {
    var rect = canvas1.getBoundingClientRect();
    var x = e.clientX - rect.left;
    var y = e.clientY - rect.top;
    console.log('正在执行  表格 插入操作'); 
    drawGrid(); // Redraw the grid to clear previous highlights
    highlightSquares(x, y); // Highlight squares based on mouse position

   
    var selected = highlightSquares(x, y);
    // tableRows=selected.columns;
    // tableLines=selected.rows;
    drawCoordinates(selected.rows, selected.columns);

  });

    var canvas = $('#myCanvas')[0];
    var ctx = canvas.getContext('2d');
    var curOnBorder=0; //光标在边框上
    var curOnBorderAndButtonDown=0; //光标在边框上且左键按钮被按下  
    var leftButtonDown=0; //左键按钮被按下
    var onBottomLine=0;   //光标在表格底部边框上

    var isMoveTable=0;    //是否在移动表格 1=是 0=否
    var isOnMoveTable=0;  //是否在移动表格的边框上 1=是 0=否

      // 定义自定义光标样式
    var myCursor = "url('imgs/down_cursor.png'), auto";

    // Attach event handlers
  // $('#myCanvas').mousemove(handleMouseMove);
  // $('#myCanvas').mouseleave(handleMouseLeave);


  function renderPostition(x, y,showText) {
    // Clear a rectangle area for the coordinates to avoid overlap
    ctx.clearRect(20, 0, 550, 16); // Clear a small area at the top-left corner
    
    // Set font properties
    ctx.font = '14px Arial';
    ctx.fillStyle = '#808080';
    ctx.textAlign = 'left'; 
    console.log('显示调整参数x:'+String(x)+' y:'+String(y));
    // Render the text
    ctx.fillText('X: ' + x + ', Y: '+y+' ('+showText+')' , 20, 8);
  }

    // Function to handle mouse movement within the canvas
  function handleMouseMove(event) {
    var rect = canvas.getBoundingClientRect();
    var x = event.clientX - rect.left;
    var y = event.clientY - rect.top;
    
    iconVisible = true; // Show the icon
    drawIcon(x, y);
  }

  // Function to hide the icon when the mouse leaves the canvas
  function handleMouseLeave() {
    iconVisible = false;
    ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
  }


// 设置阴影的函数
function setShadow(shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY) {
    ctx.shadowColor = shadowColor;
    ctx.shadowBlur = shadowBlur;
    ctx.shadowOffsetX = shadowOffsetX;
    ctx.shadowOffsetY = shadowOffsetY;
  }

  // 绘制带阴影的矩形的函数
  function drawShadowedRect(x, y, width, height, shadowColor, shadowBlur, offsetX, offsetY, fillColor) {
    setShadow(shadowColor, shadowBlur, offsetX, offsetY);
    ctx.fillStyle = fillColor;
    ctx.fillRect(x, y, width, height);
    // 重置阴影，以便之后的绘制不会受到影响
    setShadow('rgba(0, 0, 0, 0)', 0, 0, 0);
  }



  // 绘制带阴影的页面背景
  drawShadowedRect(pageX, pageY, pageWidth, pageHeight, 'rgba(0, 0, 0, 0.5)', 10, 5, 5, 'white');



     jsonData = [
    
    {
      "cells": [
        {"content": "A1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "B1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "C1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "D1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "E1", "width": 60, "height": 40, "borderSize": 1, "showBorder": true}
      ]
    },
    {
      "cells": [
        {"content": "A1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "B1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "C1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "D1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "E1", "width": 60, "height":  40, "borderSize": 1, "showBorder": true}
      ]
    },
	{
	  "cells": [
	    {"content": "A1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
	    {"content": "B1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
	    {"content": "C1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
	    {"content": "D1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
	    {"content": "E1", "width": 60, "height":  40, "borderSize": 1, "showBorder": true}
	  ]
	},
    {
      "cells": [
        {"content": "A1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "B1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "C1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "D1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
        {"content": "E1", "width": 60, "height": 40, "borderSize": 1, "showBorder": true}
      ]
    }
  // ... 其他行，以此类推

    ];
    //统计更新表格总宽度
    for(var i=0; i<jsonData.length; i++)
    {
      for(var j=0; j<jsonData[i].cells.length; j++)
      {
        var cell = jsonData[i].cells[j];
        var content = cell.content;
        var width = cell.width;
        var height = cell.height;
        var borderSize = cell.borderSize;
        var showBorder = cell.showBorder;
        lastTableTotalWidth+=width;
      }
      break;
    }

    function drawTableOnCanvas(rows, cols) {
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');

    // Calculate cell width and height
    var cellWidth = canvas.width / cols;
    var cellHeight = canvas.height / rows;

    // Clear the canvas before drawing
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw the table
    for (var i = 0; i < rows; i++) {
      for (var j = 0; j < cols; j++) {
        var x = j * cellWidth;
        var y = i * cellHeight;
        
        // Draw cell border
        ctx.strokeRect(x, y, cellWidth, cellHeight);

        // Fill cell with text
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        var text = 'Cell ' + (i+1) + ',' + (j+1);
        ctx.fillText(text, x + cellWidth / 2, y + cellHeight / 2);
      }
    }
  }



    function drawCell(ctx, cell, startX, startY, isSelected) {
      // 绘制单元格的边框
      if (cell.showBorder) {
        ctx.strokeRect(startX, startY, cell.width, cell.height);
      }
      
      // 绘制选择区域颜色
      if (isSelected) {
        ctx.fillStyle = 'lightblue';
        ctx.fillRect(startX, startY, cell.width, cell.height);
      }

      // 设置文本对齐方式，并绘制文本内容
      ctx.textBaseline = 'middle';
      ctx.textAlign = 'center';
      ctx.fillStyle = 'black';
      ctx.fillText(cell.content, startX + cell.width / 2, startY + cell.height / 2);
    }

    function drawTable(data) {
      var cellStartX = tableOffsetX;
      var cellStartY = tableOffsetY;

      data.forEach(function(rowData, rowIndex) {
        rowData.cells.forEach(function(cell, cellIndex) {
          var isCellSelected = selectedCells.some(function(selCell) {
            return selCell.row === rowIndex && selCell.col === cellIndex;
          });
          drawCell(ctx, cell, cellStartX, cellStartY, isCellSelected);
          cellStartX += cell.width; // 移动到下一个单元格的起始位置
        });
        cellStartX = tableOffsetX; // 重置X位置到行的开始
        cellStartY += rowData.cells[0].height; // 移动到下一行的起始位置
      });
    }




function drawTableFromJson(jsonData) { //绘制表格
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  canvas.width = jsonData[0].cells.reduce((acc, cell) => acc + cell.width, 0);
  canvas.height = jsonData.length * jsonData[0].cells[0].height;
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  var currentX = 0;
  var currentY = 0;

  jsonData.forEach(function(rowData, rowIndex) {
    currentX = 0;
    rowData.cells.forEach(function(cell) {
      if (cell.showBorder) {
        ctx.strokeRect(currentX, currentY, cell.width, cell.height);
      }
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.fillText(cell.content, currentX + cell.width / 2, currentY + cell.height / 2);
      currentX += cell.width;
    });
    currentY += rowData.cells[0].height;
  });
}


    function getCellFromCoords(x, y) {
      var startX = 0;
      var startY = 0;
      //遍历行
      for (var rowIndex = 0; rowIndex < jsonData.length; rowIndex++) {
        var row = jsonData[rowIndex].cells;
        //遍历列
        for (var cellIndex = 0; cellIndex < row.length; cellIndex++) {
          var cell = row[cellIndex];
          //判断点击位置是否在单元格内
          if (x >= startX && x <= startX + cell.width &&
              y >= startY && y <= startY + cell.height) {
            return {row: rowIndex, col: cellIndex};//返回单元格坐标
          }
          startX += cell.width;
        }
        startX = 0;
        startY += row[0].height;
      }

      return null;
    }

    function updateSelection(x, y) {
      var cell = getCellFromCoords(x, y);//返回x,y对应的单元格行列坐标
      if (cell && (selectionStart.row != cell.row || selectionStart.col != cell.col)) {
        currentSelection = [];
        //确定选择范围
        for (var i = Math.min(selectionStart.row, cell.row); i <= Math.max(selectionStart.row, cell.row); i++) {
          for (var j = Math.min(selectionStart.col, cell.col); j <= Math.max(selectionStart.col, cell.col); j++) {
            currentSelection.push({row: i, col: j});
          }
        }
        redraw();
      }
    }



    function redraw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      drawShadowedRect(pageX, pageY, pageWidth, pageHeight, 'rgba(0, 0, 0, 0.5)', 10, 5, 5, 'white');
      drawTable(jsonData);
      currentSelection.forEach(function(cell) {
        // var startX = cell.col * jsonData[0].cells[cell.col].width;
        // var startY = cell.row * jsonData[cell.row].cells[0].height;
        // var cellData = jsonData[cell.row].cells[cell.col];
        // drawCell(ctx, cellData, startX, startY, true);
        var cellStartX = cell.col * jsonData[0].cells[cell.col].width;
        var cellStartY = cell.row * jsonData[cell.row].cells[0].height;
        var cellData = jsonData[cell.row].cells[cell.col];
        cellStartX = cellStartX + tableOffsetX;
        cellStartY = cellStartY + tableOffsetY;
        drawCell(ctx, cellData, cellStartX, cellStartY, true);
      });
       // 绘制页面边框
  ctx.strokeStyle = '#cccccc';
  ctx.lineWidth = 1;
  ctx.strokeRect(pageX, pageY, pageWidth, pageHeight);
    }

    function redrawBySelect(startX,startY,mouseX,mouseY) {
    
      //var context = canvas.get(0).getContext('2d');
      

      ctx.clearRect(0, 0, canvas.width, canvas.height);
      drawShadowedRect(pageX, pageY, pageWidth, pageHeight, 'rgba(0, 0, 0, 0.5)', 10, 5, 5, 'white');
      drawTable(jsonData);
      currentSelection.forEach(function(cell) {
        // var startX = cell.col * jsonData[0].cells[cell.col].width;
        // var startY = cell.row * jsonData[cell.row].cells[0].height;
        // var cellData = jsonData[cell.row].cells[cell.col];
        // drawCell(ctx, cellData, startX, startY, true);
        var cellStartX = cell.col * jsonData[0].cells[cell.col].width;
        var cellStartY = cell.row * jsonData[cell.row].cells[0].height;
        var cellData = jsonData[cell.row].cells[cell.col];
        drawCell(ctx, cellData, cellStartX, cellStartY, true);
      });
       // 绘制页面边框
      ctx.strokeStyle = '#cccccc';
      ctx.lineWidth = 1;
      ctx.strokeRect(pageX, pageY, pageWidth, pageHeight);

      ctx.beginPath();
      ctx.setLineDash([5, 3]); // 保证虚线样式
      ctx.rect(startX, startY, mouseX - startX, mouseY - startY);
      ctx.stroke();
      ctx.setLineDash([]); // 保证

    }



    function updateTotalWidth()
    {
      tableTotalWidth=0;
          for(var m=0;m<tableRows;m++)
            {
              tableTotalWidth+=jsonData[0].cells[m].width;
            }
    }

    function updateTotalHeight()
    {
           tableTotalHeight=0; //重新计算表格总高
            for(var n=0;n<tableLines;n++)
            {
              tableTotalHeight+=jsonData[n].cells[0].height;
            }
    }

    $('#canvasPopup').mousedown(function(e) {
    var rect = canvas1.getBoundingClientRect();
    var x = e.clientX - rect.left;
    var y = e.clientY - rect.top;
    var selected = highlightSquares(x, y);
    
    //alert('Rows selected: ' + selected.rows + ', Columns selected: ' + selected.columns);


    console.log('正在执行  表格 插入操作 Rows selected: ' + selected.rows + ', Columns selected: ' + selected.columns); 

   
    var jsonData = generateJsonData(selected.rows, selected.columns);
  	//drawTableFromJson(jsonData);
    tableRows=selected.columns;
    tableLines=selected.rows;
    updateTotalWidth();// 重新计算表格总宽度
    updateTotalHeight();// 重新计算表格总高度
    redraw();
    // 绘制第二个图层的表格
    // drawTableOnLayer2(selected.rows, selected.columns);
    // 调用函数绘制表格
    //drawTableOnLayer2WithMargins(selected.rows, selected.columns, marginTop, marginBottom, marginLeft, marginRight);
           // 绘制页面边框
           var ctx = canvas1.getContext('2d');
  				ctx.strokeStyle = '#cccccc';
  				ctx.lineWidth = 1;
  				ctx.strokeRect(pageX, pageY, pageWidth, pageHeight);

    $('#canvasPopup').hide(); // 隐藏第一个 canvas 层




  });


      drawTable(jsonData);

       // 绘制页面边框
  ctx.strokeStyle = '#cccccc';
  ctx.lineWidth = 1;
  ctx.strokeRect(pageX, pageY, pageWidth, pageHeight);

   
      var currentSelectedCellRowIndex=0; //当前选中的单元格所在行索引
      var currentSelectedCellIndex=0;    //当前选中的单元格所在列索引
      var tableRows=0;                   //当前表格行数
      var curOnTheRightBoarder=0;         //光标在右侧边框上
      var curOnTheBottomBoarder=0;        //光标在底部边框上ing
      var tableLines=0
      var isSelectRegionDrawing = false;    //是否开始选择操作


 
    //表格区域提示图标
  var icon = new Image();
  var iconLoaded = false; // Flag to check if the icon has loaded
  var iconVisible = false; // Flag to toggle icon visibility

  // Set your PNG icon's URL
  icon.src = 'imgs/move_icon.png'; // Replace 'your-icon.png' with the path to your icon
  icon.onload = function() {
    iconLoaded = true;
   
  };

      canvas.addEventListener('mousemove', function(e) {

      var canvasOffset = $('#myCanvas').offset();

      var canvas = $('#myCanvas');
      var context = canvas.get(0).getContext('2d');
      var cursorX = event.pageX;
      var cursorY = event.pageY;

   

     
      var currentCell=null;

      var keysArray = Object.keys(jsonData);
      
	    tableLines= keysArray.length;
      
  

  

      var startX = canvasOffset.left+tableOffsetX; //画布左边，画布的X起始点
      var startY = canvasOffset.top+tableOffsetY;  //画布顶边，画布的Y起始点

    
      var found=0;
      var selectCellLeft=0;
      var selectCellTop=0;
      var selectCellRight=0;
      var selectCellBottom=0;

      var offset = 6; 				// 光标与边线的偏移量
      var curOffsetX=offset;  
      var curOffsetY=offset;
      var curOffsetMy=offset;
  
      var inRightPosition=0;

   
      
        for(var n=0;n<tableLines;n++)
        {
          tableTotalHeight+=jsonData[n].cells[0].height;
        }


        updateTotalWidth();// 初始化表格总长度
        updateTotalHeight();//初始化表格总高度
    

        // for(var m=0;m<tableRows;m++)
        // {
        //   tableTotalWidth+=jsonData[0].cells[m].width;
        // }
      //光标在边框上且左键按钮被按下 正在调整中 ,此时不做单元格OverMove监听，直到释放调整
    

      // //模拟画选择框
      // if (leftButtonDown==1) {
       
      //  var rect = canvas.get(0).getBoundingClientRect();
      // var mouseX = e.clientX - rect.left;
      // var mouseY = e.clientY - rect.top;
      // redrawBySelect(selectStartX,selectStartY,mouseX,mouseY);
   
      //  return;
      // }


      // if(isSelectRegionDrawing == true)    //是否开始选择操作
      // {
      //   if(selectStartX == 0&&selectStartY == 0)	
      //   {
      //     selectStartX=cursorX;
      //     selectStartY=cursorY;
      //   }	
      //   else
      //   {
      
      // 			context.clearRect(0, 0, canvas.width(), canvas.height()); // 清除画布
      // 			context.beginPath();
      // 			context.setLineDash([5, 3]); // 保证虚线样式
      // 			context.rect(selectStartX, selectStartY, cursorX - selectStartX, cursorY - selectStartY);
      // 			context.stroke();
      //   }			
      //   return;    
      // }


      if(isMoveTable==1)
      {
        console.log('正在执行  表格 移动操作'); 
        tableOffsetX = cursorX-canvasOffset.left;
        tableOffsetY = cursorY-canvasOffset.top;
        redraw();
        showText="正在移动表格:"+tableOffsetX+","+tableOffsetY;
        renderPostition(cursorX,cursorY,showText);
        return;
      }
      if(cursorX>startX-offset*2&&cursorX<startX&& cursorY>startY-offset*2&&cursorY<startY) //
       {
           isOnMoveTable=1;
           inRightPosition=1;
           whereCurIs=4;
           console.log('监测到    表格 移动区域：');
           var myCursor = "url('imgs/move_table_cursor.png') 16 16,auto";
           document.body.style.cursor = myCursor;
       }
       else
       {

        isMoveTable=0;
        isOnMoveTable=0;
       }

      var showText="";
      if( curOnBorder==1&&curOnBorderAndButtonDown==1)
      {

        //currentSelectedCellRowIndex=0; //当前选中的单元格所在行索引
        //currentSelectedCellIndex=0;    //当前选中的单元格所在列索引

      

        var direct='调整列宽';
        if(whereCurIs==1)
        direct='调整行高';

        //console.log('正在调整中 '+direct+' 操作方向:'+whereCurIs+' 列数：'+tableRows+' 光标坐标：(' + cursorX + ', ' + cursorY + ' curOnBorder:'+curOnBorder+', curOnBorderAndButtonDown:'+curOnBorderAndButtonDown+' 当前行：'+currentSelectedCellRowIndex+' 当前列:'+currentSelectedCellIndex+')');


        //处理光标在表格最右边的情况
        if(curOnTheRightBoarder==1)
        {
            var totalOffsetX=0;
            console.log('正在调整中 宽度---------- ');
            for(var j=0;j<currentSelectedCellIndex;j++)
            {
              
              console.log('表格最右边_调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 列号："+String(j));
                totalOffsetX+=jsonData[currentSelectedCellRowIndex].cells[j].width;//选中行下前N列的宽
        
            }
            //更新当前列单元格的宽
            for(var i=0;i<tableLines;i++)
            {
              var tempWidth=cursorX-totalOffsetX-startX;//最后一个单元格的宽，需要减去其它单元格的总宽度
              console.log('表格最右边_调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 上单元格宽度："+String(tempWidth));
              //console.log('调整单元格大小，当前更新列上单元格高度：'+);
              if(currentSelectedCellIndex>=0) //
              {
                if(tempWidth>=15)
                jsonData[i].cells[currentSelectedCellIndex].width=tempWidth;
              }
              
          
            }

            showText="最右边单元格宽："+String(tempWidth);
            //更新表格总宽度
            updateTotalWidth(); //重新计算表格总宽度
            updateTotalHeight();//重新计算表格总高度
            lastTableTotalWidth=tableTotalWidth;//记录上一次的表格总宽度
            redraw();
            renderPostition(cursorX,cursorY,showText);
            return ;
        }

        if(curOnTheBottomBoarder==1)//处理光标在表格最下边的情况
        {

          var totalOffsetY=0;
            for(var j=0;j<tableLines-1;j++)
            {
              
              console.log('表格最下边_curOnTheBottomBoarder==1 调整单元格大小，当前更新列:'+j+" 列号：0 单元格高："+String(jsonData[j].cells[0].height));
                totalOffsetY+=jsonData[j].cells[0].height;//最一行之前N行高之和
        
            }

            var currentRowHeight=cursorY-startY-totalOffsetY; //最后一行的高度正在变化，所以要减去前面的行高
            showText="最下边单元格高："+String(currentRowHeight);
            //更新当最后一行单元格的高
            for(var i=0;i<tableRows;i++)
            {
             
              console.log('表格最下边_curOnTheBottomBoarder==1 调整单元格大小，当前更新行:'+currentSelectedCellIndex+" 上单元格宽度："+String(currentRowHeight));
              //console.log('调整单元格大小，当前更新列上单元格高度：'+);
              if(tableLines>=0)
              {
                if(curOnTheBottomBoarder==1)
                {
                  if(currentRowHeight>=15)
                  jsonData[tableLines-1].cells[i].height=currentRowHeight; //对最后一行进行更新
                }
               
              }
              
          
            }

            tableTotalHeight=0
            updateTotalHeight(); //重新计算表格总高

            redraw();
            renderPostition(cursorX,cursorY,showText);
            return ;

        }

        if(whereCurIs==1)//调整行高:同一行所有单元格的行高都改变，bottom的Y值等于cursorY
        {
			      //计算当前单元格上面所有单元格的高度。tableLines
            var totalOffsetY=0;
            for(var j=0;j<currentSelectedCellRowIndex;j++)
            {
              if(j<currentSelectedCellRowIndex-1)
              {
                totalOffsetY+=jsonData[j].cells[0].height;
              }
                      
            }
            //更新当前行单元格的高度
            for(var i=0;i<tableRows;i++)
            {
              var tempHeight=cursorY-startY-totalOffsetY;
              console.log('调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 上单元格高度："+String(tempHeight));
              //console.log('调整单元格大小，当前更新列上单元格高度：'+);
			        if(currentSelectedCellRowIndex-1>=0)
              {
                if(tempHeight>=15)
                jsonData[currentSelectedCellRowIndex-1].cells[i].height=tempHeight;
              }
             
			 
            }
            if(tempHeight>=15)
            {
              showText="当前调整单元格高："+String(tempHeight);
            }
            else
            {
              showText="当前调整单元格高：16";
            }
            
        }
		
		if(whereCurIs==2)//调整列单元格宽,左侧调整列宽，右则也相反方向调整列宽
		{
			//计算当前单元格上面所有单元格的宽度。tableLines
			var totalOffsetX=0; //调整列之前的单元格总宽
      var restOffsetX=0;  //调整列之后的单元格总宽
     
      
			for(var j=0;j<currentSelectedCellIndex-1;j++)
			{
				
        //console.log('调整单元格大小==》，当前更新列:'+currentSelectedCellRowIndex+" 列号："+String(j));
        if(j<tableRows)
				totalOffsetX+=jsonData[currentSelectedCellRowIndex].cells[j].width;//选中行下前N列的宽
	
			} 

      for(var j=currentSelectedCellIndex+1;j<tableRows;j++) 
      {
        console.log('j:'+String(j)+'行先:'+String(currentSelectedCellRowIndex+1));
        if(currentSelectedCellRowIndex+1<=tableLines)
          restOffsetX+=jsonData[0].cells[j].width;//选中行下后N列的宽
          
        
       
      }
      
        var tempWidth=cursorX-startX-totalOffsetX; //计算出当前光标左列的宽度，
        var afterCellWidth=jsonData[0].cells[currentSelectedCellIndex].width;//光标右则的单元格更新后的高，计算值；
        //如果光标在最后一列，最后一是列的宽度小于15后，向左拉时，表格最右边保持不变
        if(afterCellWidth>=15)
        {
          afterCellWidth=lastTableTotalWidth-totalOffsetX-cursorX+startX;
        }
       
        
        if(currentSelectedCellIndex>=0&&currentSelectedCellIndex<tableRows)
        {
            //记录当前单元格左边和右边单元格的宽度
            var currentLeftCellWidth=jsonData[0].cells[currentSelectedCellIndex-1].width; //左边表格
            var currentRightCellWidth=jsonData[0].cells[currentSelectedCellIndex].width; //右边表格
						console.log('选中列：'+currentSelectedCellIndex+'当前表格总宽度：'+String(tableTotalWidth)+' totalOffsetX：'+String(totalOffsetX+tempWidth)+' restWidth:'+String(restOffsetX)+' 上一次表格总宽度:'+String(lastTableTotalWidth)+'calculate total:'+String(currentLeftCellWidth+currentRightCellWidth+restOffsetX+totalOffsetX));
          

           
            //如果宽度变小，则需要调整右边表格的宽度
            var subWidth= currentLeftCellWidth-tempWidth;//老的宽度-变化后的宽度

            if(tempWidth>0)//左单元格比之前变小，右则的单元格宽度需要变宽
            {
              if((totalOffsetX+tempWidth+restOffsetX)<lastTableTotalWidth-15)
              {
                if((jsonData[0].cells[currentSelectedCellIndex].width-subWidth)>=15)//后面的单元格宽度足够
              	{
                 afterCellWidth=currentRightCellWidth+subWidth;
              	}  		 
              }
              else
              {
                return;
              }
                       
             
            }
            else//变窄
            {
              afterCellWidth=currentRightCellWidth-subWidth;
            }

        }
         

     

 

      //更新当前列单元格的宽
        if(lastTableTotalWidth-totalOffsetX+tempWidth-restOffsetX<0)//判读光标后一列单元格小于16
        {
          
          	
              afterCellWidth=16;
              tempWidth=lastTableTotalWidth-totalOffsetX-afterCellWidth-restOffsetX;        
           
          // console.log('越过总长度:'+String(totalOffsetX+tempWidth+afterCellWidth)+' afterCellWidth:'+String(afterCellWidth)+ ' TableTotalWidth:'+String(tableTotalWidth)+' tempCounterTotalOffsetX:'+String(tempCounterTotalOffsetX));
          // curOnBorder=0;
          //  return;
        }
        //当最新表宽大于旧表宽时，需要调整列宽
        if((totalOffsetX+afterCellWidth+restOffsetX+tempWidth)<lastTableTotalWidth)
        {
          if(tempWidth<=15)
          {
             tempWidth=15;
          }
         
          afterCellWidth=lastTableTotalWidth-totalOffsetX-tempWidth-restOffsetX;
          console.log('总长度受影响越:'+String(totalOffsetX+afterCellWidth+restOffsetX+tempWidth)+' afterCellWidth:'+String(afterCellWidth)+ ' TableTotalWidth:'+String(tableTotalWidth)+' tempCounterTotalOffsetX:'+String(tempCounterTotalOffsetX));
        
        }

        //修正总表宽度大于最新表宽度时，需要调整列宽
        if((totalOffsetX+tempWidth+afterCellWidth+restOffsetX)>lastTableTotalWidth)
        {
          afterCellWidth=lastTableTotalWidth-totalOffsetX-tempWidth-restOffsetX;
          //console.log('总长度受影响大越:'+String(totalOffsetX+afterCellWidth+restOffsetX+tempWidth)+' afterCellWidth:'+String(afterCellWidth)+ ' TableTotalWidth:'+String(tableTotalWidth)+' tempCounterTotalOffsetX:'+String(tempCounterTotalOffsetX));
      
        }
      
        showText="左单元格宽:"+String(tempWidth)+" 右单元格宽:"+String(afterCellWidth);
     
        // var tempCounterTotalOffsetX=0; //调整列之前的单元格总宽
        // for( var j=0;j<tableRows;j++)
        // {
        //   tempCounterTotalOffsetX+=jsonData[currentSelectedCellRowIndex].cells[j].width;
          
        // }
        // if(tempCounterTotalOffsetX>lastTableTotalWidth)
        // {
        //   console.log('===========调整后大于:'+String(totalOffsetX+afterCellWidth+restOffsetX+tempWidth))
        //   return;
        // }
		    for(var i=0;i<tableLines;i++)
		    {   
          
		      //console.log('调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 上单元格宽度："+String(tempWidth));
		    
			  if(currentSelectedCellIndex-1>=0&currentSelectedCellIndex<tableRows)
        {
      
          if(tempWidth>=15)
          {
            jsonData[i].cells[currentSelectedCellIndex-1].width=tempWidth; //左单元格宽设定

            if(afterCellWidth>=15)
            {
              console.log('最后一个单元格列宽大于15：'+String(afterCellWidth));
                  jsonData[i].cells[currentSelectedCellIndex].width=afterCellWidth;
            }        
            else
            {  //小于或等于15
              console.log('最后一个单元格列宽 小于15：'+String(afterCellWidth));
              var myWidth=lastTableTotalWidth-totalOffsetX-currentLeftCellWidth-restOffsetX;
              jsonData[i].cells[currentSelectedCellIndex].width=myWidth;
            }

            //console.log('调整单元格大小，后表格=》马上赋值：'+String(subWidth));

          }

        }
		      
			 
		    }
      
		}
		var floatOnBoard=0;
		//isSelecting = false;
		    currentSelection = [];
        updateTotalHeight();// 重新计算表格总高度
        redraw();
        renderPostition(cursorX,cursorY,showText);
        return;
      }
      
      
      $('#cursorCoordinates').text('光标坐标监控全局：(' + cursorX + ', ' + cursorY +')');

 

      //表格选中监测=========================================================================================================
      //遍历行
      var cellStartX = canvasOffset.left+tableOffsetX;
      var cellStartY = canvasOffset.top+tableOffsetY;
      for (var rowIndex = 0; rowIndex < tableLines; rowIndex++) {
      
        var row = jsonData[rowIndex].cells; //表格行单元格数组
         //遍历行中的每个单元格       
         //遍历列 
         if(row.length>0)
         tableRows=row.length;
         //console.log('=====当前 遍历列:(' + rowIndex +')'+'光标坐标：(' + cursorX + ', ' + cursorY +') 表格共有列数:'+String(tableRows) );
        
				//遍历每一列，是不是在选中范围内
        for (var cellIndex = 0; cellIndex < row.length; cellIndex++) { 
          // 获取单元格的位置信息
          console.log();
          var cell = row[cellIndex];//当前行第N个的单元格
          //startX表格起始点x坐标
          //startY表格起始点y坐标
         
          //console.log('rowIndex:(' + rowIndex +' cellIndex:'+cellIndex+')  单元格位置：cell.x:(' + String(cellStartX) +' cell.y:'+String(cellStartY)+')'+' 光标坐标：(' + cursorX + ','+ cursorY + ')');
          //console.log('rowIndex:(' + rowIndex +' cellIndex:'+cellIndex+')  单元格位置：cell.x:(' + startX +' cell.y:'+startY+')'+' 光标坐标：(' + cursorX + ', ' + cursorY + ')');
          if (cursorX >= cellStartX && cursorX <= cellStartX + cell.width &&
              cursorY >= cellStartY && cursorY <= cellStartY + cell.height) {
                
         
            console.log('=====光标在所在 行:(' + rowIndex +' 列:'+cellIndex+')');

       			if(isSelecting==true)
            {
              cursorIsInSideOfCell=1;
            }
            else
            {
              if((cellStartX+offset)<cursorX&& //光标X在左则偏移右边
              cursorX<(cellStartX+cell.width-offset)&&//光标X在右则偏移左边
              (cellStartY+offset)<cursorY&&//光标Y在上则偏移下边
              cursorY<(cellStartY+cell.height-offset))//光标Y在下则偏移上边
              {
                cursorIsInSideOfCell=1;
                console.log('光标在单元格内心==============');
              }
              else
							{
                cursorIsInSideOfCell=0;
                console.log('光标不在单元格内心==============');
              }



         	
            }
           

            selectCellLeft=cellStartX;
            selectCellTop=cellStartY;
            selectCellRight=cellStartX+cell.width;
            selectCellBottom=cellStartY+cell.height;
            document.body.style.cursor = 'default';
            currentCell = cell;
            found=1;
            
            if(cellIndex==tableLines)//光标在最后一行
            {
              //console.log('光标在最后一列 =rowIndex:(' + rowIndex +' cellIndex:'+cellIndex+')');
            }
            if(curOnBorderAndButtonDown==0) //只有在结构上没有按下按钮时，才进行选中
            {
              currentSelectedCellRowIndex=rowIndex;
              currentSelectedCellIndex=cellIndex;
            }
           
            break;
          }
          cellStartX += cell.width;
        }
        if(found==1 )
        break;
        cellStartX = startX;
        cellStartY += row[0].height;
      }
     
      if(found==1) //当光标在表格上时，显示左上角的移动表格提示图标
      {
        //if (iconVisible) {
         // Draw the icon
         ctx.drawImage(icon, tableOffsetX - icon.width, tableOffsetY - icon.height);
        // console.log('开始画图标===============)');
        //}
      }
      else
      {
        console.log('清除开始画图标===============)');
        isSelecting = false;
        currentSelection = [];
        selectedCells = selectedCells.concat(currentSelection);
        
     
        cursorIsInSideOfCell=0;
       
    
        redraw();
      }

         //表格选中功能
         if (isSelecting) {
         var canvas = $('#myCanvas');
        // var context = canvas.get(0).getContext('2d');
         var rect = canvas.get(0).getBoundingClientRect();
       
         var x = e.clientX - rect.left;
         var y = e.clientY - rect.top;
        /*
         tableOffsetX = cursorX-canvasOffset.left;
         tableOffsetY = cursorY-canvasOffset.top;
        */
        x=cursorX-canvasOffset.left-tableOffsetX;
        y=cursorY-canvasOffset.top-tableOffsetY;
        updateSelection(x, y);
        console.log('==========表格选中设置x ：'+String(x)+" y: "+String(y)+' whereCurIs:'+String(whereCurIs));
				redraw();
        return;
      }

        //光标表格在最右边。OK 
        if((tableTotalWidth-offset+startX)<cursorX&&cursorX<(tableTotalWidth+offset+startX)&&cursorY>startY&&cursorY<(tableTotalHeight+startY)&&cursorY>startY)
         {
          //光标在表格的最右边上
           curOnTheRightBoarder=1;
           whereCurIs=2;
           var myCursor = "url('imgs/l_r_cursor.png') 16 16,auto";
           document.body.style.cursor = myCursor;
           //console.log('监测到 光标在表格最右边边边------------------totalWidth:'+tableTotalWidth+' cursorX:'+cursorX+' offset:'+offset);
            return;
        
         }
         else
         {
           curOnTheRightBoarder=0;

         }


         //curOnTheBottomBoarder
         if((tableTotalHeight-curOffsetY+startY)<cursorY&&cursorY<(tableTotalHeight+curOffsetY+startY))
         {
          //光标在表格的最下边上
           curOnTheBottomBoarder=1;
           whereCurIs=4;
           var myCursor = "url('imgs/u_d_cursor.png') 16 16,auto";
            document.body.style.cursor = myCursor;
            //console.log('监测到 光标在表格最下边边边------------------totalWidth:'+tableTotalWidth+' cursorX:'+cursorX+' offset:'+offset);
            return;
         }else
         {
           curOnTheBottomBoarder=0;
         }

        //光标在单元格上方，立即更新光标为上下双箭头,调整高度的情形
       if(cursorX>startX&&cursorX<(tableTotalWidth+startX)&&cursorY>(selectCellTop-offset)&&cursorY<(selectCellTop+offset))
       {
           
            if(currentSelectedCellRowIndex==0)
            {
              //光标在第一行的上边，变光标为单向下箭头
              var myCursor = "url('imgs/down_cursor.png') 8 8,auto";
              document.body.style.cursor = myCursor;
              inRightPosition=1;
              whereCurIs=3;
              //console.log('监测到 光标在单元格首行顶线上-------------------');

            }
            else
            {
              //console.log('监测到  光标在单元格的上边线上 当前行：'+currentSelectedCellRowIndex+' 当前列:'+currentSelectedCellIndex);
              var myCursor = "url('imgs/u_d_cursor.png') 16 16,auto";
              document.body.style.cursor = myCursor;//上下双箭头
              //document.body.style.cursor = 'ns-resize';//上下双箭头
              inRightPosition=1;
              whereCurIs=1;

            }

            floatOnBoard=1;
           
       }
 
   

     
        //光标在左侧边，立即更新光标为左右双箭,调节宽度的情形
       if(cursorX>(selectCellLeft-offset)&&cursorX<(selectCellLeft+offset)&&cursorY>startY&&cursorY<(tableTotalHeight+startY))      
       {

       // console.log('监测到 光标在单元格首行最左边线上：-------------------：：：'+currentSelectedCellIndex);
            if(currentSelectedCellIndex==0)//光标在第一列的左边
            {
               //光标在第一行的上边，变光标为单向下箭头
               var myCursor = "url('imgs/right_cursor.png')8 8, auto";
              document.body.style.cursor = myCursor;
             // console.log('光标在单元格首行最左边线上-------------------');
           
            }
            else
            {
              //document.body.style.cursor = 'ew-resize';//左右双箭头
             // console.log('光标在单元格左边线上-------------------');
             var myCursor = "url('imgs/l_r_cursor.png') 16 16,auto";
              document.body.style.cursor = myCursor;//左右双箭头
            }
           
           
            floatOnBoard=1;
            inRightPosition=1;//在正确的位置上
            whereCurIs=2;
       }
       

       if(inRightPosition==0)
        {
          document.body.style.cursor = 'default';
        }
       else
        {  
          if(cursorIsInSideOfCell==1)//光标在单元格内心
          {
            floatOnBoard=0;//光标不在边线上
            whereCurIs=5;//光标在单元格内心
          }
          else
          {
          
          }
          

          if(floatOnBoard==1)
          {
            console.log('在表格边上悬浮 1,光标在单元格的上边线上, 2光标在左侧边; 3光标在第一行的上边; 4，在最下边单元格；5光标在单元格内部 ：'+ String(whereCurIs));
            curOnBorder=1;
          }
          else
          {
            curOnBorder=0;
            console.log('不在表格边上悬浮  1,光标在单元格的上边线上, 2光标在左侧边; 3光标在第一行的上边; 4，在最下边单元格； 5光标在单元格内部  ：'+ String(whereCurIs));
          }
         
        }

      if(curOnBorderAndButtonDown==1)
      {
       
        if(whereCurIs==1)//光标在单元格上方，调节高度
        { 
          console.log('调整单元格大小，当前所在行:'+currentSelectedCellRowIndex+" 表格列数： "+tableRows);
          if(currentSelectedCellRowIndex!=0)//第一行不处理
          {

            //更新当前行单元格的高度
            for(var i=0;i<tableRows;i++)
            {
              //console.log('调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 上单元格高度："+cursorY-canvasOffset);
              //jsonData[currentSelectedCellRowIndex].cells[i].height=cursorY-selectCellTop-canvasOffset;
            }
            
          }

        }



      }
      
   


      
    });
  /*===================================================================
  OnMouseUp 处理鼠标释放事件
  =====================================================================*/

    canvas.addEventListener('mouseup', function(e) {

      if (e.which === 1) 
      {
          e.preventDefault();
      }

      
    if (isSelecting) {
       
      isSelecting=false;
        // if(cursorIsInSideOfCell==0)
        // {
        //      selectedCells = [];
        // 		currentSelection = [];
        // 		cursorIsInSideOfCell=0;	
        //      isSelecting = false;
        // }
     
        console.log('表格选择鼠标左键被释放。');
        var canvas = $('#myCanvas');
     		var context = canvas.get(0).getContext('2d');
     		var rect = canvas.get(0).getBoundingClientRect();
     	
	
         var x = event.pageX;
         var y = event.pageY;
         


       showMenu(x, y);
        // redraw();
      }

    if(curOnTheRightBoarder==1)//当调节单元格右边框时，释放。
    {
      
      curOnTheRightBoarder=0;  
      curOnTheBottomBoarder=0;
      curOnBorder=0;//释放单元格边线
      curOnBorderAndButtonDown=0;
      console.log('表格最右侧单元格鼠标左键被释放。');
      return;
    }
    if(isMoveTable==1)
    {
      isMoveTable=false;
      isOnMoveTable=false
      curOnTheRightBoarder=0;  
      curOnTheBottomBoarder=0;
      curOnBorder=0;//释放单元格边线
      curOnBorderAndButtonDown=0;
      console.log('表格移动状态鼠标左键被释放。');
    }

    if(curOnTheBottomBoarder==1)
    {
      curOnTheBottomBoarder=0;
      curOnTheRightBoarder=0;  
      curOnBorder=0;//释放单元格边线
      curOnBorderAndButtonDown=0;
      console.log('表格最下行鼠标左键被释放。');
      return;  
    }

	 if( curOnBorder==1&&curOnBorderAndButtonDown==1)
	 { curOnBorderAndButtonDown=0;//释放单元格调整按钮
     curOnBorder=0;//释放单元格边线
     document.body.style.cursor ='default';//恢复默认光标
     console.log('表格调整键被释放。');
	   return;//在调整时，不做选择操作。
		 
	 }
   isSelectRegionDrawing = false;    //是否开始选择操作
  
      
    });


  /*===================================================================
      OnMouseDown 处理鼠标左键按下事件
  =====================================================================*/
    canvas.addEventListener('mousedown', function(e) {
		

      // if (event.which === 3) {

      //   curOnTheRightBoarder=0;//释放单元格边线
      //   curOnBorder=0;//释放单元格边线
      //   curOnBorderAndButtonDown=0;//释放单元格调整按钮
      // // 处理鼠标右键事件
      // console.log('鼠标右键被按下。');

      
      // // 阻止默认的右键菜单
      // event.preventDefault();

      //     selectedCells = []; // Clear previous selection, if we want to support multiple selections we should not clear this
      //     currentSelection = [selectionStart];
      //     redraw();
      //     return;

      // }

      //leftButtonDown=1;
     		var canvas = $('#myCanvas');
     		var context = canvas.get(0).getContext('2d');
     		var rect = canvas.get(0).getBoundingClientRect();
     		var canvasOffset = canvas.offset();
	
         var cursorX = event.pageX;
         var cursorY = event.pageY;

      	var x = e.clientX - rect.left;
      	var y = e.clientY - rect.top;
          x=cursorX-canvasOffset.left-tableOffsetX;
          y=cursorY-canvasOffset.top-tableOffsetY;
        selectionStart = getCellFromCoords(x, y);//获取开始单元格
        
      if (selectionStart&&cursorIsInSideOfCell==1) {

        console.log('鼠标左键被按下 获取开始单元格 进入选择状态:-----------------:'+selectionStart+' x="'+String(x)+'" y="'+String(y)+'"');  
        isSelecting = true;
        selectedCells = []; // Clear previous selection, if we want to support multiple selections we should not clear this
        currentSelection = [selectionStart];
        redraw();
        return;
      }


 

      if(isOnMoveTable==1)//光标在表格左上，，置可移动表格
      {
        curOnBorder=1;
        var myCursor = "url('imgs/move_table_cursor.png') 16 16,auto";
        document.body.style.cursor = myCursor;
        curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下  
        isMoveTable=1;  //置表格可移动
        console.log('表格左上角 鼠标左键被按下。');
        return;
      }

     //光标在表格的最右边上
     if(curOnTheRightBoarder==1)
     {
                var myCursor = "url('imgs/l_r_cursor.png') 16 16,auto";
                document.body.style.cursor = myCursor;
                curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下  

                curOnBorder=1;

               

                console.log('表格最右边上鼠标左键被按下。');
                return;
     }

         //光标在表格的最下边上
    if(curOnTheBottomBoarder==1)
     {
                var myCursor = "url('imgs/u_d_cursor.png') 16 16,auto";
                document.body.style.cursor = myCursor;
                curOnTheBottomBoarder=1; 
                curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下

                curOnBorder=1;

               

                console.log('表格最下边上鼠标左键被按下。');
                return;
     }
          
            
  
    if( curOnBorder==1)         //光标在边框上
    {
      console.log('光标在边框上-鼠标左键被按下。');
      curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下  
      return;
    }
    
     isSelectRegionDrawing = true;    //是否开始选择操作
  
     var canvas = $('#myCanvas');
     var context = canvas.get(0).getContext('2d');
     var rect = canvas.get(0).getBoundingClientRect();
    
       
        var x = e.clientX - rect.left;
        var y = e.clientY - rect.top;
        x=x-canvasOffset.left-tableOffsetX;
        y=y-canvasOffset.top-tableOffsetY;

        selectionStart = getCellFromCoords(x, y);
        if (selectionStart) {
          isSelecting = true;
          selectedCells = []; // Clear previous selection, if we want to support multiple selections we should not clear this
          currentSelection = [selectionStart];
          redraw();
        }
  
       
  
      });


   
  });
</script>

</body>
</html>
